var util = {};

util.imessage = function(msg, redirect, type) {
	var wuiMessage = {};
	if(redirect) {
		var redirectType = redirect.substring(0, 9), url = '', open_type = '';
		if(redirectType == 'navigate:') {
			open_type = 'navigate';
			url = redirect.substring(9);
		} else if(redirectType == 'redirect:') {
			open_type = 'redirect';
			url = redirect.substring(9);
		} else if(redirect.substring(0, 10) == 'switchTab:') {
			open_type = 'switchTab';
			url = redirect.substring(10);
		} else {
			open_type = 'redirect';
			url = redirect;
		}
	}
	if(typeof msg == 'object') {
		wuiMessage = {
			show : 1,
			type: type ? type : 'info',
			title: msg.title,
			message: msg.message,
			btn_text: msg.btn_text,
			open_type: open_type,
			url: url
		};
	} else {
		wuiMessage = {
			show : 1,
			type: type ? type : 'info',
			title: msg,
			open_type: open_type,
			url: url
		};
	}
	var curPage = util.getCurPage();
	curPage.setData({
		wuiMessage: wuiMessage,
	});
	wx.setNavigationBarTitle({
		title: '系统提示'
	})
	wx.setNavigationBarColor({
		frontColor: '#000000',
		backgroundColor: '#ffffff',
		animation: {
			duration: 400,
			timingFunc: 'easeIn'
		}
	});
	return;
};

util.jump2url = function(url, redirectFunction) {
	var redirectFunction = redirectFunction ? redirectFunction : 'redirectTo';
	wx[redirectFunction]({
		url: url,
		fail: function(res) {
			wx.switchTab({
				url: url,
				fail: function() {
					wx.redirectTo({
						url: url
					});
				}
			});
		}
	});
};

util.toast = function(msg, url, timeout) {
	let pages = getCurrentPages();
	let curPage = pages[pages.length - 1];
	var wuiToast = curPage.data.wuiToast || {};
	clearTimeout(wuiToast.timer);
	curPage.setData({
		wuiToast: {
			show: true,
			title: msg,
			url: url
		}
	});
	var timer = setTimeout(function() {
		clearTimeout(wuiToast.timer);
		curPage.setData({
			'wuiToast.show': false
		});
		//跳转url
		var redirect = curPage.data.wuiToast.url;
		if(!redirect) {
			return;
		}
		if(redirect == 'back') {
			wx.navigateBack();
		} else if(redirect == 'refresh') {
			curPage.onLoad();
		} else {
			var redirectType = redirect.substring(0, 9), url = '', redirectFunction = '';
			if (redirectType == 'navigate:') {
				redirectFunction = 'navigateTo';
				redirect = redirect.substring(9);
			} else if(redirectType == 'redirect:') {
				redirectFunction = 'redirectTo';
				redirect = redirect.substring(9);
			} else if(redirect.substring(0, 10) == 'switchTab:') {
				redirectFunction = 'switchTab';
				redirect = redirect.substring(10);
			} else {
				redirect = redirect;
				redirectFunction = 'navigateTo';
			}
			wx[redirectFunction]({
				url: redirect,
				fail: function(res) {
					wx.switchTab({
						url: redirect,
						fail: function() {
							wx.redirectTo({
								url: redirect
							});
						}
					});
				}
			});
			return false;
		}
	}, timeout || 3000);

	curPage.setData({
		'wuiToast.timer': timer
	});
};

util.getCurPage = function() {
	let pages = getCurrentPages();
	let curPage = pages[pages.length - 1];
	return curPage;
};

util.setNavigator = function(tabBar, position){
	let curPage = util.getCurPage();
	position = Object.assign({
		bottom: '150px',
		right: '10px',
	}, position);
	curPage.setData({
		wuiNavigator: {
			show: false,
			tabBar: tabBar,
			position: position
		}
	});
};

util.loading = function(){
	let curPage = util.getCurPage();
	curPage.setData({
		wuiLoading: {
			show: true
		}
	});
};

util.loaded = function(){
	let curPage = util.getCurPage();
	curPage.setData({
		wuiLoading: {
			show: false
		}
	});
};

util.jsInfinite = function(e) {
	var curPage = util.getCurPage(), dataSet = e.currentTarget.dataset;
	var min = dataSet.min, href = dataSet.href, name = dataSet.name;
	if(!id || !href || curPage.data.loading == 1) {
		return false;
	}
	curPage.data.loading = 1;
	curPage.setData({
		showloading: true
	});
	util.request({
		url: href,
		data: { min: min },
		success: function (res) {
			var result = res.data.message;
			if(result.errno) {
				util.toast(result.message);
				return;
			}
			var records = that.data.redPackets.concat(result.message);
			if(!records.length) {
				that.setData({
					showNodata: true,
					showloading: false
				});
				return false;
			}
			var data = {
				min: result.min,
				showloading: false
			};
			data[name] = records;
			if(!res.data.message.min) {
				data.min = -1;
			}
			that.setData(data);
			return true
		}
	});
};

util.gohome = function() {
	wx.switchTab({
		url: '/pages/home/index',
		fail: function(res) {
			if(res.errMsg == 'switchTab:fail can not switch to no-tabBar page' || res.errMsg == 'switchTab:fail:can not switch to non-TabBar page') {
				wx.redirectTo({
					url: '/pages/diy/index'
				});
			}
		}
	});
	return true;
};

util.jsEvent = function(e) {
	var obj = e.currentTarget.dataset;
	var type = obj.eventType || 'jsPost';
	if(type == 'jsPost') {
		util.jsPost(e);
	} else if(type == 'jsPay') {
		util.jsPay(e);
	} else if(type == 'jsUrl') {
		util.jsUrl(e);
	} else if(type == 'jsPhone') {
		util.jsPhone(e);
	} else if(type == 'jsToggle') {
		util.jsToggle(e);
	} else if(type == 'jsLocation') {
		util.jsLocation(e);
	} else if(type == 'jsCopy') {
		util.jsCopy(e);
	} else if(type == 'webview'){
		util.webview(e);
	} else if(type == 'jsInfinite'){
		util.jsInfinite(e);
	} else if(type == 'jsToggleNavigator'){
		let curPage = util.getCurPage();
		curPage.setData({
			'wuiNavigator.show': !curPage.data.wuiNavigator.show
		});
	} else if(type == 'jsSaveImg'){
		util.jsSaveImg(e);
	} else if(type == 'jsUploadImg') {
		util.jsUploadImg(e);
	} else if(type == 'jsDelImg') {
		util.jsDelImg(e);
	}
	return;
};

util.jsUrl = function(e) {
	var url = e.currentTarget.dataset.url;
	if(!url) {
		util.toast('请先设置跳转链接');
		return false;
	}
	url = url.split(':');
	if(url.length == 1){
		url = '/' + url[0];
		wx.navigateTo({
			url: url,
			fail: function(res) {
				console.log(res);
				wx.switchTab({
					url: url,
					fail: function() {
						wx.redirectTo({
							url: url
						});
					}
				});
			}
		});
		return;
	} else {
		if(url[0] == 'webview') {
			util.webview(e);
		} else if(url[0] == 'tel'){
			util.jsPhone(e);
		} else if(url[0] == 'miniProgram'){
			util.jsMiniProgram(e);
		} else if(url[0] == 'wx') {
			if(url[1] == 'scanCode') {
				wx.scanCode();
			}
		}
	}
}

//增加订阅消息次数
util.requestSubscribeMessage = function(params) {
	if(!params) {
		params = {};
	}
	var templateIds = util.getStorageSync('templateIds');
	var type = params.type ? params.type : 'order';
	templateIds = templateIds[type]
	if(!templateIds || !templateIds.length) {
		util.toast('订阅消息模板ID不存在');
		return false;
	}
	wx.requestSubscribeMessage({
		tmplIds: templateIds,
		success: function (res) {
			console.log('调起订阅消息success', res);
			if(typeof params.success == "function") {
				params.success(res);
				return false;
			}
		},
		fail: function (res) {
			console.log('调起订阅消息fail', res);
			if(typeof params.fail == "function") {
				params.fail(res);
				return false;
			}
		},
		complete: function (res) {
			console.log('调起订阅消息complete', res);
		}
	})
},

util.jsMiniProgram = function(e) {
	var obj =	e.currentTarget.dataset;
	if(obj.url && obj.url.indexOf(':') != -1) {
		var getUrls = obj.url.split(':');
		var datas	= getUrls[1].split(',');
		var params = {};
		for(var i = 0; i < datas.length; i++) {
			var item = datas[i].split('_');
			params[item[0]] = item[1];
		}
	} else {
		var params = {
			appId: obj.appid || obj.appId
		};
		if(obj.path) {
			params['path'] = path;
		}
	}
	wx.navigateToMiniProgram(params);
	return;
};

util.tolink = function(link) {
	if(link.indexOf('http://') != -1 || link.indexOf('https://') != -1) {
		return link;
	}
	var ext = util.getExtConfigSync();
	if(link.indexOf('./') == 0) {
		return ext.siteInfo.sitebase + '/' + link.replace('./', '');
	}
	return '';
}

util.webview = function(e) {
	var obj = e.currentTarget.dataset;
	if(!obj.url) {
		return false;
	}
	var getUrl = obj.url.split(':');
	if(getUrl[0] == 'webview'){
		obj.url = getUrl[1] + ':' + getUrl[2];
	}
	var url = util.tolink(obj.url), src = obj.src || '../public/webview';
	url = url.replace('?', '_a_');
	url = url.replace(/=/g, '_b_');
	url = url.replace(/&/g, '_c_');
	wx.navigateTo({
		url: src+'?url=' + url
	});
}

util.jsDelImg = function(e) {
	var obj = e.currentTarget.dataset;
	var dataKey = obj.key, index = obj.index;
	var curPage = util.getCurPage();
	var imgs = curPage.data[dataKey];
	imgs.splice(index, 1);
	var params = {};
	params[dataKey] = imgs;
	curPage.setData(params);
};

util.jsSaveImg = function(e) {
	var obj =	e.currentTarget.dataset;
	var url = obj.url;
	wx.showLoading({
		title: '正在下载中'
	});
	wx.downloadFile({
		url: url,
		success: function(res) {
			if(res.statusCode === 200) {
				wx.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success: function() {
						wx.hideLoading();
						app.util.toast('文件保存成功');
					}
				})
			}
		}
	})
};

util.jsUploadImg = function(e) {
	var obj = e.currentTarget.dataset;
	var dataKey = obj.key, count = obj.count || 9;
	var curPage = util.getCurPage();
	util.image({
		count: count,
		success: function(file) {
			curPage.data[dataKey].push(file);
			var params = {};
			params[dataKey] = curPage.data[dataKey];
			curPage.setData(params);
		}
	});
};

util.jsPhone = function(e) {
	var obj = e.currentTarget.dataset;
	var phonenumber = obj.phonenumber || obj.url;
	var phone = phonenumber.split(':');
	if(phone[0] == 'tel'){
		phonenumber = phone[1];
	}
	wx.makePhoneCall({
		phoneNumber: phonenumber
	})
}

util.jsLocation = function(e) {
	var obj = e.currentTarget.dataset;
	var lat = parseFloat(obj.lat), lng = parseFloat(obj.lng);
	if(!lat || !lng) {
		return false;
	}
	var params = {
		latitude: lat,
		longitude: lng
	};
	if(obj.scale) {
		params.scale = obj.scale;
	}
	if(obj.name) {
		params.name = obj.name;
	}
	if(obj.address) {
		params.address = obj.address;
	}
	wx.openLocation(params);
}

util.jsCopy = function(e) {
	var obj = e.currentTarget.dataset;
	wx.setClipboardData({
		data: obj.text || '',
		success: function(res) {
			wx.getClipboardData({
				success: function(res) {
					util.toast('复制成功');
				}
			})
		}
	})
};

util.jsToggle = function(e) {
	var obj = e.currentTarget.dataset;
	var curPage = util.getCurPage();
	var modal = obj.modal, arrs = obj.modal.split('.');
	var data = {};
	if(arrs.length == 1) {
		data[modal] = !curPage.data[modal];
		curPage.setData(data);
	} else {
		var value = !curPage.data[arrs[0]][arrs[1]];
		data[modal] = value;
		curPage.setData(data);
	}
	return true;
};

util.jsPay = function(e) {
	var obj = e.currentTarget.dataset;
	var successUrl = obj.successUrl, orderId = obj.orderId, orderType = obj.orderType;
	wx.navigateTo({
		url: '../public/pay?order_id=' + orderId + '&order_type=' + orderType + '&success_url=' + successUrl
	});
	return true;
};

util.jsPost = function(e) {
	var obj =	e.currentTarget.dataset;
	var confirm = obj.confirm, url = obj.href || obj.url, successUrl = obj.successUrl;
	var curPage = util.getCurPage();
	var handler = function() {
		if(curPage.data.jspost && curPage.data.jspost == 1) {
			return;
		}
		curPage.data.jspost = 1;
		util.showLoading();
		if(!successUrl) {
			successUrl = 'refresh';
		}
		util.request({
			url: util.url(url),
			data: {},
			success: function (res) {
				curPage.data.jspost = 0;
				wx.hideLoading();
				var result = res.data.message;
				var errno = result.errno, message = result.message;
				if(!errno) {
					if(!successUrl) {
						successUrl = 'refresh';
					}
					util.toast(message, successUrl);
				} else {
					util.toast(message);
				}
			}
		});
	};
	if(confirm) {
		wx.showModal({
			title: '',
			content: confirm,
			success: function(res) {
				if(res.confirm) {
					handler();
				} else if(res.cancel) {
				}
			}
		});
	} else {
		handler();
	}
};

util.setData = function(key, params) {
	var keys = key.split('.'), curPage = util.getCurPage();
	if(keys.length == 1) {
		curPage.data[key] = params;
	} else if(keys.length == 2) {
		var all = curPage.data[keys[0]];
		if(!all) {
			all = {};
		}
		all[keys[1]] = params;
		curPage.data[keys[0]] = all;
	} else if(keys.length == 3) {
		var all = curPage.data[keys[0]];
		if(!all) {
			all = {};
		}
		if(!all[keys[1]]) {
			all[keys[1]] = {};
		}
		all[keys[1]][keys[2]] = params;
		curPage.data[keys[0]] = all;
	} else if(keys.length == 4) {
		var all = curPage.data[keys[0]];
		if(!all) {
			all = {};
		}
		if(!all[keys[1]]) {
			all[keys[1]] = {};
		}
		if(!all[keys[1]][keys[2]]) {
			all[keys[1]][keys[2]] = {};
		}
		all[keys[1]][keys[2]][keys[3]] = params;
		curPage.data[keys[0]] = all;
	}
	return true;
}

util.setStorageSync = function(key, params, expire) {
	var keys = key.split('.');
	if(expire > 0) {
		var date = new Date();
		params['expire'] = parseInt(date.getTime() / 1000) + expire;
	}
	if(keys.length == 1) {
		wx.setStorageSync(key, params);
	} else if(keys.length == 2) {
		var all = wx.getStorageSync(keys[0]);
		if(!all) {
			all = {};
		}
		all[keys[1]] = params;
		wx.setStorageSync(keys[0], all);
	} else if(keys.length == 3) {
		var all = wx.getStorageSync(keys[0]);
		if(!all) {
			all = {};
		}
		if(!all[keys[1]]) {
			all[keys[1]] = {};
		}
		all[keys[1]][keys[2]] = params;
		wx.setStorageSync(keys[0], all);
	}
	return true;
}

util.getStorageSync = function(key) {
	var keys = key.split('.');
	var data = '';
	if(keys.length == 1) {
		data = wx.getStorageSync(key);
	} else if(keys.length == 2) {
		var all = wx.getStorageSync(keys[0]);
		if(all && all[keys[1]]) {
			data = all[keys[1]];
		}
	} else if(keys.length == 3) {
		var all = wx.getStorageSync(keys[0]);
		if(all && all[keys[1]]) {
			data = all[keys[1]][keys[2]];
		}
	}
	if(data && data.expire) {
		var date = new Date();
		if(data.expire < (date.getTime() / 1000)) {
			data = {};
		}
	}
	return data;
};

util.getExtConfigSync = function(key) {
	var app = getApp();
  var ext = app.ext;
	if(!key) {
		return ext;
	}
	if(!key) {
		return ext;
	}
	var keys = key.split('.');
	if(keys.length == 1) {
		return ext[keys[0]];
	} else if(keys.length == 2) {
		if(ext[keys[0]]) {
			return ext[keys[0]][keys[1]];
		}
		return '';
	} else if(keys.length == 3) {
		if(ext[keys[0]] && ext[keys[0]][keys[1]]) {
			return ext[keys[0]][keys[1]][keys[2]];
		}
		return '';
	}
	return data;
};

util.wxappversion = function() {
	var ext = util.getExtConfigSync();
	if(!ext.siteInfo.version) {
		ext.siteInfo.version = '未知';
	}
	return ext.siteInfo.version;
};


util.removeStorageSync = function(key) {
	var keys = key.split('.');
	if(keys.length == 1) {
		wx.removeStorageSync(key);
	} else if(keys.length == 2) {
		var all = wx.getStorageSync(keys[0]);
		if(all) {
			delete(all[keys[1]]);
			wx.setStorageSync(keys[0], all);
		}
	} else if(keys.length == 3) {
		var all = wx.getStorageSync(keys[0]);
		if(all && all[keys[1]]) {
			delete(all[keys[1]][keys[2]]);
			wx.setStorageSync(keys[0], all);
		}
	}
	return true;
};

util.merge = function(params1, params2) {
	var _ = require('underscore.js');
	if(!params1) {
		params1 = {};
	}
	if(!params2) {
		params2 = {};
	}
	return _.extend(params1, params2);
};

util.pay = function(params) {
	if(!params.pay_type) {
		params.pay_type = 'wechat';
	}
	if(!params.order_type) {
		return false;
	}
	if(!params.order_id) {
		return false;
	}
	var postData = {
		pay_type: params.pay_type,
		order_type: params.order_type,
		id: params.order_id
	};
	var curPage = util.getCurPage();
	util.request({
		url: 'manage/pay/pay',
		data: postData,
		success: function (result) {
			var result = result.data.message;
			if(result.errno) {
				if(result.errno == -1000) {
					//使用余额支付，余额不足
					curPage.setData({
						submitDisabled: 0
					});
				}
				util.toast(result.message);
				return false;
			}
			result = result.message;
			var routers = {
				advertise: {
					url_detail: './list'
				}
			};
			var router = routers[params.order_type];
			if(params.pay_type == 'wechat') {
				wx.requestPayment({
					'timeStamp': result.timeStamp,
					'nonceStr': result.nonceStr,
					'package': result.package,
					'signType': 'MD5',
					'paySign': result.paySign,
					'success':function(res){
						if(typeof params.success == "function") {
							params.success(res);
							return false;
						} else {
							if(router) {
								util.toast('支付成功', router.url_detail, 3000);
								return false;
							}
						}
					},
					'fail':function(res){
						if(typeof params.fail == "function") {
							params.fail(res);
							return false;
						} else {
							curPage.setData({
								submitDisabled: 0
							});
						}
					}
				});
				return true;
			} else if(params.pay_type == 'credit') {
				//余额支付和货到付款执行到这里， 一定是支付成功的状态
				if(typeof params.success == "function") {
					params.success(res);
					return false;
				}
			} else if(params.pay_type == 'delivery' || params.pay_type == 'finishMeal') {
				if(typeof params.success == "function") {
					params.success(res);
					return false;
				}
			}

			//支付成功后页面跳转
			if(router) {
				util.toast('支付成功', router.url_detail, 3000);
				return true;
			}
			return false;
		}
	});
}

/**
 构造微擎地址,
 @params action 微擎系统中的controller, action, do，格式为 'wxapp/home/navs'
 @params querystring 格式为 {参数名1 : 值1, 参数名2 : 值2}
 */
util.url = function (action, querystring) {
	var ext = util.getExtConfigSync();
	var url = ext.siteInfo.siteroot + '?i=' + ext.siteInfo.uniacid;
	if(action.indexOf('/') == -1) {
		return url + '&' +action;
	}
	url = ext.siteInfo.siteroot + '?i=' + ext.siteInfo.uniacid + '&v=' + ext.siteInfo.version + '&m=we7_wmall&c=entry&do=mobile&';
	var urls = action.split('?');
	action = urls[0].split('/');
	if (action[0]) {
		url += 'ctrl=' + action[0] + '&';
	}
	if (action[1]) {
		url += 'ac=' + action[1] + '&';
	}
	if (action[2]) {
		url += 'op=' + action[2] + '&';
	}
	if (action[3]) {
		url += 'ta=' + action[3] + '&';
	}
	if( urls[1]) {
		url += urls[1] + '&';
	}
	querystring = typeof querystring === 'object' ? querystring : {};
	if (querystring && typeof querystring === 'object') {
		for (let param in querystring) {
			if (param && querystring.hasOwnProperty(params) && querystring[param]) {
				url += param + '=' + querystring[param] + '&';
			}
		}
	}
	url += '&from=wxapp&w=manager';
	return url;
}

util.getUrlQuery = function(url) {
	var theRequest = [];
	if (url.indexOf("?") != -1) {
		var str = url.split('?')[1];
		var strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			if (strs[i].split("=")[0] && unescape(strs[i].split("=")[1])) {
				theRequest[i] = {
					'name': strs[i].split("=")[0],
					'value': unescape(strs[i].split("=")[1])
				}
			}
		}
	}
	return theRequest;
}
/*
 * 获取链接某个参数
 * url 链接地址
 * name 参数名称
 */
function getUrlParam(url, name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	var r = url.split('?')[1].match(reg);	//匹配目标参数
	if (r != null) return unescape(r[2]); return null; //返回参数值
}
/**
 二次封装微信wx.request函数、增加交互体全、配置缓存、以及配合微擎格式化返回数据

 @params option 弹出参数表，
 {
	url : 同微信,
	data : 同微信,
	header : 同微信,
	method : 同微信,
	success : 同微信,
	fail : 同微信,
	complete : 同微信,
}
 */
util.request = function (option) {
	var option = option ? option : {};
	option.showLoading = typeof option.showLoading != 'undefined' ? option.showLoading : true;
	if(!option.data) {
		option.data = {};
	}
	var url = option.url;
	if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
		url = util.url(url);
	}
	var clerkInfo = wx.getStorageSync('clerkInfo');
	var token = getUrlParam(url, 'token');
	if (!token && clerkInfo && clerkInfo.token) {
		url = url + '&token=' + clerkInfo.token;
	} else {
		if(option.data.forceOauth == 1) {
			util.getUserInfo();
			return;
		}
	}
	var msessionid = wx.getStorageSync('msessionid');
	var state = getUrlParam(url, 'state');
	if (!state && msessionid) {
		url = url + '&state=we7sid-' + msessionid;
	} else {
		console.log('===商户小程序sessionid为空======');
	}
	var sid = wx.getStorageSync('__sid');
	if(!sid && option.data.nosid != 1) {
		wx.removeStorageSync('__sid');
		wx.redirectTo({
			url: '/pages/shop/select'
		});
		return;
	} else {
		url = url + '&sid=' + sid;
	}
	wx.showNavigationBarLoading();
	if (option.showLoading) {
		util.showLoading();
	}
	console.log(url);
	wx.request({
		'url': url,
		'data': option.data ? option.data : {},
		'method': option.method ? option.method : 'GET',
		'header': {
			'content-type': 'application/x-www-form-urlencoded'
		},
		'success': function (response) {
			wx.hideNavigationBarLoading();
			wx.hideLoading();
			if(!response.data.message) {
				console.log(response.data.message)
			}
			wx.setStorageSync('msessionid', response.data.global.sessionid);
			var global = '';
			if(response.data && response.data.global) {
				global = response.data.global;
				if(global.DollarType) {
					util.setStorageSync('DollarType', global.DollarType);
				}
				if(global.noticeChannel) {
					util.setStorageSync('noticeChannel', global.noticeChannel);
				}
				if(global.templateIds) {
					util.setStorageSync('templateIds', global.templateIds);
				}
			}
			if(response.data.message.errno) {
				if (response.data.message.errno == '41009') {
					wx.setStorageSync('clerkInfo', '');
					wx.setStorageSync('__sid', 0);
					util.getUserInfo();
					return;
				} else if(response.data.message.errno == '41002') {
					wx.removeStorageSync('__sid');
					wx.redirectTo({
						url: '/pages/shop/select'
					});
					return;
				}
			}
			if(option.success && typeof option.success == 'function') {
				option.success(response);
			}
		},
		'fail': function (response) {
			if(response && response.errMsg != 'request:ok') {
				wx.hideLoading();
				if(response.errMsg == 'request:fail url not in domain list') {
					util.toast('您没有设置小程序服务器域名!注意：每次小程序发布后，都需要重新设置服务器域名，程序每个月可修改5次服务器域名。设置步骤：进入微信公众号平台-登陆小程序账号密码进入管理中心-设置-开发设置-服务器域名(服务器域名为模块授权域名)', '', 100000);
					return;
				}
				util.toast(response.errMsg);
				return;
			}
			wx.hideNavigationBarLoading();
			wx.hideLoading();
			if (option.fail && typeof option.fail == 'function') {
				option.fail(response);
			}
		},
		'complete': function (response) {
			console.log(response)
			if(response && response.errMsg != 'request:ok') {
				wx.hideLoading();
				if(response.errMsg == 'request:fail url not in domain list') {
					util.toast('您没有设置小程序服务器域名!注意：每次小程序发布后，都需要重新设置服务器域名，程序每个月可修改5次服务器域名。设置步骤：进入微信公众号平台-登陆小程序账号密码进入管理中心-设置-开发设置-服务器域名(服务器域名为模块授权域名)', '', 100000);
					return;
				}
				util.toast(response.errMsg);
				return;
			}
			wx.hideNavigationBarLoading();
			wx.hideLoading();
			if (option.complete && typeof option.complete == 'function') {
				option.complete(response);
			}
		}
	});
}

/*
 * 新订单提醒
 */
util.orderNotice = function(options) {
	var clerkInfo = wx.getStorageSync('clerkInfo');
	var sid = wx.getStorageSync('__sid');

	const backgroundAudioManager = wx.getBackgroundAudioManager();
	backgroundAudioManager.title = '您有新的订单';

	if(clerkInfo && clerkInfo.token && sid) {
		setInterval(function() {
			util.request({
				url: 'manage/common/orderNotice',
				success: function(res) {
					var result = res.data.message;
					if(!result.errno) {
						backgroundAudioManager.src = result.message.audioSrc;
					} else {
						backgroundAudioManager.stop();
						return;
					}
				}
			})
		}, 30000);
	}
}
/*
 * 图片上传
 */
util.image = function(options) {
	var count = options.count ? options.count : 9;
	var pages = getCurrentPages();
	var curPage = pages[pages.length - 1];
	wx.chooseImage({
		count: count,
		sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
		success: function (res) {
			// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
			var tempFilePaths = res.tempFilePaths;
			if(tempFilePaths.length && tempFilePaths.length > 0) {
				for(var i = 0; i < tempFilePaths.length; i++) {
					wx.uploadFile({
						url: util.url('c=utility&a=file&do=upload&type=image&thumb=0'),
						filePath: tempFilePaths[i],
						name: 'file',
						success: function(result){
							result.data = JSON.parse(result.data);
							typeof options.success == "function" && options.success(result.data);
						}
					})
				}
			}
		}
	})
},

util.uploadOpenid = function () {
	var clerkInfo = wx.getStorageSync('clerkInfo');
	if(clerkInfo.openid_wxapp_manager) {
		return;
	}
	if(!clerkInfo.token) {
		return;
	}
	wx.login({
		success: function (res) {
			util.request({
				url: 'system/common/auth/openid',
				data: { code: res.code, token: clerkInfo.token, type: 'manager' },
				cachetime: 0,
				success: function (res) {
					if(res.data.message.errno) {
						wx.showModal({
							content: res.data.message.message
						});
					}
					return;
				}
			});
		}
	});
}

/*
 * 获取用户信息
 */
util.getUserInfo = function(cb) {
	wx.redirectTo({
		url: '/pages/auth/index'
	});
	return true;
},

util.getLocation = function (callback) {
	wx.getLocation({
		type: 'gcj02',
		success: function (data) {
			util.request({
				url: 'system/common/map/regeo',
				data: {latitude: data.latitude, longitude: data.longitude, convert: 0},
				success: function (location) {
					typeof callback == "function" && callback(location);
				},
				fail: function(data) {

				}
			});
		},
		fail: function(res) {
			if(res && res.errMsg == 'getLocation:fail auth deny') {
				wx.showModal({
					title: '授权提示',
					content: '若需使用平台，平台需要获取您的位置信息',
					confirmText: '授权',
					showCancel: false,
					success: function(res) {
						if(res.confirm) {
							wx.openSetting({
								success: function() {}
							});
						} else if(res.cancel) {
						}
					}
				});
			}
		}
	});
}

util.getLocationPois = function(params) {
	util.request({
		url: 'system/common/map/regeo',
		data: {
			latitude: params.latitude,
			longitude: params.longitude
		},
		showLoading: params.showLoading === false ? params.showLoading : true,
			success: function(result) {
			var location = result.data.message.message;
			typeof params.success == "function" && params.success(location);
		},
		fail: function (data) {
		}
	});
}

util.getLocationAround = function(params) {
	util.request({
		url: 'system/common/map/place_around',
		data: {
			latitude: params.latitude,
			longitude: params.longitude,
			keywords: params.keywords,
			radius: params.radius
		},
		success: function(result) {
			var location = result.data.message.message;
			typeof params.success == "function" && params.success(location);
		},
		fail: function (data) {
		}
	});
}

util.navigateBack = function (obj) {
	let delta = obj.delta ? obj.delta : 1;
	if (obj.data) {
		let pages = getCurrentPages()
		let curPage = pages[pages.length - (delta + 1)];
		if (curPage.pageForResult) {
			curPage.pageForResult(obj.data);
		} else {
			curPage.setData(obj.data);
		}
	}
	wx.navigateBack({
		delta: delta, // 回退前 delta(默认为1) 页面
		success: function (res) {
			// success
			typeof obj.success == "function" && obj.success(res);
		},
		fail: function (err) {
			// fail
			typeof obj.fail == "function" && obj.function(err);
		},
		complete: function () {
			// complete
			typeof obj.complete == "function" && obj.complete();
		}
	})
};

util.footer = function (that) {
	let app = getApp();
	let tabBar = app.tabBar;
	for(let i in tabBar['list']) {
		tabBar['list'][i]['pageUrl'] = tabBar['list'][i]['pagePath'].replace(/(\?|#)[^"]*/g, '')
	}
	tabBar.thisurl = that.__route__;
	that.setData({
		tabBar: tabBar
	});
};
/*
 * 提示信息
 * type 为 success, error 当为 success,	时，为toast方式，否则为模态框的方式
 * redirect 为提示后的跳转地址, 跳转的时候可以加上 协议名称
 * navigate:/we7/pages/detail/detail 以 navigateTo 的方法跳转，
 * redirect:/we7/pages/detail/detail 以 redirectTo 的方式跳转，默认为 redirect
 */
util.message = function(title, redirect, type) {
	if (!title) {
		return true;
	}
	if (typeof title == 'object') {
		redirect = title.redirect;
		type = title.type;
		title = title.title;
	}
	if (redirect) {
		var redirectType = redirect.substring(0, 9), url = '', redirectFunction = '';
		if (redirectType == 'navigate:') {
			redirectFunction = 'navigateTo';
			url = redirect.substring(9);
		} else if (redirectType == 'redirect:') {
			redirectFunction = 'redirectTo';
			url = redirect.substring(9);
		} else {
			url = redirect;
			redirectFunction = 'redirectTo';
		}
	}
	if (!type) {
		type = 'success';
	}
	if (type == 'success') {
		wx.showToast({
			title: title,
			icon: 'success',
			duration: 2000,
			mask : url ? true : false,
			complete : function() {
				if (url) {
					setTimeout(function(){
						wx[redirectFunction]({
							url: url
						});
					}, 1800);
				}

			}
		});
	} else if (type == 'error') {
		wx.showModal({
			title: '系统信息',
			content : title,
			showCancel : false,
			complete : function() {
				if (url) {
					wx[redirectFunction]({
						url: url
					});
				}
			}
		});
	}
}

util.user = util.getUserInfo;

//封装微信等待提示，防止ajax过多时，show多次
util.showLoading = function() {
	var isShowLoading = wx.getStorageSync('isShowLoading');
	if (isShowLoading) {
		wx.hideLoading();
		wx.setStorageSync('isShowLoading', false);
	}

	wx.showLoading({
		title : '加载中',
		complete : function() {
			wx.setStorageSync('isShowLoading', true);
		},
		fail : function() {
			wx.setStorageSync('isShowLoading', false);
		}
	});
}

util.showImage = function(event) {
	var url = event ? event.currentTarget.dataset.preview : '';
	var current = event ? event.currentTarget.dataset.current : '';
	if (!url) {
		return false;
	}
	var urls = [];
	if(Array.isArray(url)) {
		urls = url;
	} else {
		urls.push(url);
	}
	wx.previewImage({
		urls: urls,
		current: current
	});
}

util.isMobile = function(mobile) {
	var reg = /^[01][3456789][0-9]{9}$/;
	var LocalDollarType = wx.getStorageSync('DollarType');
	if(LocalDollarType != '' && LocalDollarType != 'zh-cn') {
		reg = /^\d{5,}$/;
	}
	if(!reg.test(mobile)) {
		return false;
	}
	return true;
}


/**
 * 转换内容中的emoji表情为 unicode 码点，在Php中使用utf8_bytes来转换输出
 */
util.parseContent = function(string) {
	if (!string) {
		return string;
	}

	var ranges = [
		'\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
		'\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
		'\ud83d[\ude80-\udeff]'	// U+1F680 to U+1F6FF
	];
	var emoji = string.match(
		new RegExp(ranges.join('|'), 'g'));

	if (emoji) {
		for (var i in emoji) {
			string = string.replace(emoji[i], '[U+' + emoji[i].codePointAt(0).toString(16).toUpperCase() + ']');
		}
	}
	return string;
}

util.date = function(){
	/**
	 * 判断闰年
	 * @param date Date日期对象
	 * @return boolean true 或false
	 */
	this.isLeapYear = function(date){
		return (0==date.getYear()%4&&((date.getYear()%100!=0)||(date.getYear()%400==0)));
	}

	/**
	 * 日期对象转换为指定格式的字符串
	 * @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
	 * @param date Date日期对象, 如果缺省，则为当前时间
	 *
	 * YYYY/yyyy/YY/yy 表示年份
	 * MM/M 月份
	 * W/w 星期
	 * dd/DD/d/D 日期
	 * hh/HH/h/H 时间
	 * mm/m 分钟
	 * ss/SS/s/S 秒
	 * @return string 指定格式的时间字符串
	 */
	this.dateToStr = function(formatStr, date){
		formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
		date = arguments[1] || new Date();
		var str = formatStr;
		var Week = ['日','一','二','三','四','五','六'];
		str=str.replace(/yyyy|YYYY/,date.getFullYear());
		str=str.replace(/yy|YY/,(date.getYear() % 100)>9?(date.getYear() % 100).toString():'0' + (date.getYear() % 100));
		str=str.replace(/MM/,date.getMonth()>9?(date.getMonth() + 1):'0' + (date.getMonth() + 1));
		str=str.replace(/M/g,date.getMonth());
		str=str.replace(/w|W/g,Week[date.getDay()]);

		str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0' + date.getDate());
		str=str.replace(/d|D/g,date.getDate());

		str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0' + date.getHours());
		str=str.replace(/h|H/g,date.getHours());
		str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0' + date.getMinutes());
		str=str.replace(/m/g,date.getMinutes());

		str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0' + date.getSeconds());
		str=str.replace(/s|S/g,date.getSeconds());

		return str;
	}


	/**
	 * 日期计算
	 * @param strInterval string	可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
	 * @param num int
	 * @param date Date 日期对象
	 * @return Date 返回日期对象
	 */
	this.dateAdd = function(strInterval, num, date){
		date =	arguments[2] || new Date();
		switch (strInterval) {
			case 's' :return new Date(date.getTime() + (1000 * num));
			case 'n' :return new Date(date.getTime() + (60000 * num));
			case 'h' :return new Date(date.getTime() + (3600000 * num));
			case 'd' :return new Date(date.getTime() + (86400000 * num));
			case 'w' :return new Date(date.getTime() + ((86400000 * 7) * num));
			case 'm' :return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
			case 'y' :return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
		}
	}

	/**
	 * 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串
	 * @param strInterval string	可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
	 * @param dtStart Date	可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
	 * @param dtEnd Date	可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
	 */
	this.dateDiff = function(strInterval, dtStart, dtEnd) {
		switch (strInterval) {
			case 's' :return parseInt((dtEnd - dtStart) / 1000);
			case 'n' :return parseInt((dtEnd - dtStart) / 60000);
			case 'h' :return parseInt((dtEnd - dtStart) / 3600000);
			case 'd' :return parseInt((dtEnd - dtStart) / 86400000);
			case 'w' :return parseInt((dtEnd - dtStart) / (86400000 * 7));
			case 'm' :return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);
			case 'y' :return dtEnd.getFullYear() - dtStart.getFullYear();
		}
	}

	/**
	 * 字符串转换为日期对象
	 * @param date Date 格式为yyyy-MM-dd HH:mm:ss，必须按年月日时分秒的顺序，中间分隔符不限制
	 */
	this.strToDate = function(dateStr){
		var data = dateStr;
		var reCat = /(\d{1,4})/gm;
		var t = data.match(reCat);
		t[1] = t[1] - 1;
		eval('var d = new Date('+t.join(',')+');');
		return d;
	}

	/**
	 * 把指定格式的字符串转换为日期对象yyyy-MM-dd HH:mm:ss
	 *
	 */
	this.strFormatToDate = function(formatStr, dateStr){
		var year = 0;
		var start = -1;
		var len = dateStr.length;
		if((start = formatStr.indexOf('yyyy')) > -1 && start < len){
			year = dateStr.substr(start, 4);
		}
		var month = 0;
		if((start = formatStr.indexOf('MM')) > -1	&& start < len){
			month = parseInt(dateStr.substr(start, 2)) - 1;
		}
		var day = 0;
		if((start = formatStr.indexOf('dd')) > -1 && start < len){
			day = parseInt(dateStr.substr(start, 2));
		}
		var hour = 0;
		if( ((start = formatStr.indexOf('HH')) > -1 || (start = formatStr.indexOf('hh')) > 1) && start < len){
			hour = parseInt(dateStr.substr(start, 2));
		}
		var minute = 0;
		if((start = formatStr.indexOf('mm')) > -1	&& start < len){
			minute = dateStr.substr(start, 2);
		}
		var second = 0;
		if((start = formatStr.indexOf('ss')) > -1	&& start < len){
			second = dateStr.substr(start, 2);
		}
		return new Date(year, month, day, hour, minute, second);
	}


	/**
	 * 日期对象转换为毫秒数
	 */
	this.dateToLong = function(date){
		return date.getTime();
	}

	/**
	 * 毫秒转换为日期对象
	 * @param dateVal number 日期的毫秒数
	 */
	this.longToDate = function(dateVal){
		return new Date(dateVal);
	}

	/**
	 * 判断字符串是否为日期格式
	 * @param str string 字符串
	 * @param formatStr string 日期格式， 如下 yyyy-MM-dd
	 */
	this.isDate = function(str, formatStr){
		if (formatStr == null){
			formatStr = "yyyyMMdd";
		}
		var yIndex = formatStr.indexOf("yyyy");
		if(yIndex==-1){
			return false;
		}
		var year = str.substring(yIndex,yIndex+4);
		var mIndex = formatStr.indexOf("MM");
		if(mIndex==-1){
			return false;
		}
		var month = str.substring(mIndex,mIndex+2);
		var dIndex = formatStr.indexOf("dd");
		if(dIndex==-1){
			return false;
		}
		var day = str.substring(dIndex,dIndex+2);
		if(!isNumber(year)||year>"2100" || year< "1900"){
			return false;
		}
		if(!isNumber(month)||month>"12" || month< "01"){
			return false;
		}
		if(day>getMaxDay(year,month) || day< "01"){
			return false;
		}
		return true;
	}

	this.getMaxDay = function(year,month) {
		if(month==4||month==6||month==9||month==11)
			return "30";
		if(month==2)
			if(year%4==0&&year%100!=0 || year%400==0)
				return "29";
			else
				return "28";
		return "31";
	}
	/**
	 *	变量是否为数字
	 */
	this.isNumber = function(str)
	{
		var regExp = /^\d+$/g;
		return regExp.test(str);
	}

	/**
	 * 把日期分割成数组 [年、月、日、时、分、秒]
	 */
	this.toArray = function(myDate)
	{
		myDate = arguments[0] || new Date();
		var myArray = Array();
		myArray[0] = myDate.getFullYear();
		myArray[1] = myDate.getMonth();
		myArray[2] = myDate.getDate();
		myArray[3] = myDate.getHours();
		myArray[4] = myDate.getMinutes();
		myArray[5] = myDate.getSeconds();
		return myArray;
	}

	/**
	 * 取得日期数据信息
	 * 参数 interval 表示数据类型
	 * y 年 M月 d日 w星期 ww周 h时 n分 s秒
	 */
	this.datePart = function(interval, myDate)
	{
		myDate = arguments[1] || new Date();
		var partStr='';
		var Week = ['日','一','二','三','四','五','六'];
		switch (interval)
		{
			case 'y' :partStr = myDate.getFullYear();break;
			case 'M' :partStr = myDate.getMonth()+1;break;
			case 'd' :partStr = myDate.getDate();break;
			case 'w' :partStr = Week[myDate.getDay()];break;
			case 'ww' :partStr = myDate.WeekNumOfYear();break;
			case 'h' :partStr = myDate.getHours();break;
			case 'm' :partStr = myDate.getMinutes();break;
			case 's' :partStr = myDate.getSeconds();break;
		}
		return partStr;
	}

	/**
	 * 取得当前日期所在月的最大天数
	 */
	this.maxDayOfDate = function(date)
	{
		date = arguments[0] || new Date();
		date.setDate(1);
		date.setMonth(date.getMonth() + 1);
		var time = date.getTime() - 24 * 60 * 60 * 1000;
		var newDate = new Date(time);
		return newDate.getDate();
	}
};

util.parseScene = function(scene) {
	var scene = decodeURIComponent(scene);
	scene = scene.split('/');
	var parseScene = {};
	for(var i = 0; i < scene.length; i++) {
		scene[i] = scene[i].split(':');
		var key = scene[i][0];
		var value = scene[i][1];
		parseScene[key] = value;
	}
	return parseScene;
};

util.setSid = function(sid) {
	var __sid = util.getStorageSync('__sid');
	if(sid && sid != __sid) {
		util.setStorageSync('__sid', sid);
	}
	return true;
};

util.getCaptcha = function(params) {
	if(!params.url) {
		return false;
	}
	wx.downloadFile({
		url: params.url,
		header: {
			'content-type': 'image/png',
		},
		success: function(res) {
			console.log(111, res);
			let currentPage = util.getCurPage();
			let data = {};
			if(params.srcName) {
				data[params.srcName] = res.tempFilePath;
			} else {
				data['captcha'] = res.tempFilePath;
			}
			currentPage.setData(data)
			return res.tempFilePath;
		},
		fail: function(res) {
			util.toast('图形验证码下载错误');
		}
	})
};

module.exports = util;